﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using MyFramework.Core.Models;
using MyFramework.Plugins.Core.Core;
using MyFramework.Web.Api;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MyFramework.Plugins.Core.Controllers
{
    /// <summary>
    /// 插件接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize]
    public class PluginsController : ControllerBase
    {
        private readonly ApplicationPartManager _applicationPartManager;
        private readonly MyPluginManager _myPluginManager;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="applicationPartManager"></param>
        /// <param name="myPluginManager"></param>
        public PluginsController(ApplicationPartManager applicationPartManager
            , MyPluginManager myPluginManager
            //, IHostingEnvironment env
            )
        {
            _applicationPartManager = applicationPartManager;
            _myPluginManager = myPluginManager;
            // _hostingEnvironment = env;
        }
        /// <summary>
        /// 生成程序集
        /// </summary>
        /// <remarks>
        /// 请求示例
        ///  
        ///     Demo
        /// </remarks>
        /// <param name="pluginName"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResponse> GenerateAssembly(string pluginName = "Demo")
        {
            ApiResponse apiResponse = new ApiResponse();
            //MyAssemblyLoadContext context = new MyAssemblyLoadContext();
            //CompileAssemblyHelper.CompileAssembly(pluginName);
            return await Task.FromResult(apiResponse);
        }

        /// <summary>
        /// 编译
        /// </summary>
        /// <remarks>
        /// 请求示例
        ///  
        ///     Demo
        /// </remarks>
        /// <param name="pluginName"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ApiResponse> Compile(string pluginName = "Demo")
        {
            ApiResponse apiResponse = new ApiResponse();
            MyAssemblyLoadContext context = new MyAssemblyLoadContext();
            CompileAssemblyHelper.CompileAssembly(pluginName);
            return Task.FromResult(apiResponse);
        }

        /// <summary>
        /// 启用
        /// </summary>
        /// <remarks>
        /// 请求示例
        ///  
        ///     Demo
        /// </remarks>
        /// <param name="pluginName"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ApiResponse> Load(string pluginName = "Demo")
        {
            var a= MyPluginPathProvider.SourceCode;
            ApiResponse apiResponse = new ApiResponse();
            _myPluginManager.Load(pluginName);
            return Task.FromResult(apiResponse);
        }
        /// <summary>
        /// 卸载
        /// </summary>
        /// <remarks>
        /// 请求示例
        ///  
        ///     Demo
        /// </remarks>
        /// <param name="pluginName"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<ApiResponse> Unload(string pluginName = "Demo")
        {
            ApiResponse apiResponse = new ApiResponse();
            _myPluginManager.Unload(pluginName);
            return Task.FromResult(apiResponse);
        }
        /// <summary>
        /// 启用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NonAction]
        public Task<ApiResponse> Enable()
        {
            /*
             *注意事项
             *System.Runtime.Loader.AssemblyLoadContext.Default默认上下文不建议使用 程序集无法单独移除和卸载 如需热更新及卸载 需使用单独的上下文
             */
            ApiResponse apiResponse = new ApiResponse();
            string assemblyPath = @"E:\project\my\MyFramework\code\MyFramework\Sample\NetCore\MyFramework.Web.Api.Sample\assembly\MyFramework.Web.Api.Test.Sample.dll";
            assemblyPath = @"E:\project\my\MyFramework.Plugins.Core\code\MyFramework.Plugins.Core\MyFramework.Plugins.Core\ClassLibrary1\bin\Debug\netcoreapp3.1\ClassLibrary1.dll";
            //var assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
            Assembly assembly = Assembly.Load(System.IO.File.ReadAllBytes(assemblyPath));

            AssemblyPart assemblyPart = new AssemblyPart(assembly);
            if (assembly != null)
            {
                try
                {
                    ApplicationPart last = _applicationPartManager.ApplicationParts.FirstOrDefault(m =>
                    {
                        return m.Name == assemblyPart.Name;
                    }
                    );
                    _applicationPartManager.ApplicationParts.Remove(last);
                }
                catch (Exception ex)
                {

                }
                _applicationPartManager.ApplicationParts.Add(assemblyPart);
                // Notify change
                MyActionDescriptorChangeProvider.Instance.HasChanged = true;
                // TokenSource 为 null
                // 注意: 在程序刚启动时, 未抵达 Controller 时不会触发 IActionDescriptorChangeProvider.GetChangeToken(), 也就会导致 TokenSource 为 null, 在启动时，同时在启动时，插件Controller.Action和主程序一起被添加，此时无需通知改变
                if (MyActionDescriptorChangeProvider.Instance.TokenSource != null)
                {
                    // 只有在插件列表控制启用，禁用时才需通知改变
                    MyActionDescriptorChangeProvider.Instance.TokenSource.Cancel();
                }
            }

            assemblyPath = @"E:\project\my\MyFramework.Plugins.Core\code\MyFramework.Plugins.Core\MyFramework.Plugins.Core\ClassLibrary2\bin\Debug\netcoreapp3.1\ClassLibrary2.dll";

            AssemblyLoadContext assemblyLoadContext = new AssemblyLoadContext(null);
            assemblyLoadContext.LoadFromStream(new FileStream(assemblyPath, FileMode.Open));
            //System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(new FileStream(assemblyPath, FileMode.Open));
            return Task.FromResult(apiResponse);
        }
    }
}
